require("dotenv").config();
const Koa = require("koa");
const bodyParser = require("koa-bodyparser");
const mongoose = require("mongoose");
const path = require("path");
const serve = require("koa-static");
const router = require("./routers");
const cors = require('@koa/cors');

const app = new Koa();

app.use(cors());

// 连接 MongoDB
mongoose.connect(process.env.MONGO_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
const db = mongoose.connection;
db.on("error", console.error.bind(console, "MongoDB 连接错误："));
db.once("open", () => console.log("MongoDB 连接成功"));

// 指定图片资源文件夹，例如 'public/images'
const staticPath = path.join(__dirname, 'public/uploads');
app.use(serve(staticPath), { maxage: 1000 * 60 * 60 * 2 });


// 中间件
app.use(bodyParser());
app.use(router.routes()).use(router.allowedMethods());

// 监听端口
const PORT = process.env.PORT || 8088;
app.listen(PORT, () => console.log(`服务器运行在 http://localhost:${PORT}`));
